const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const path = require('path')
const DataStore = require('./renderer/musicDataStore.js')
const myStore = new DataStore({ name: 'Music Data' })

app.whenReady().then(() => {
  //创建主窗口
  const mainWindow = new AppWindow({}, 'index')
  //监听主框架及同步资源加载完成（不包括异步动态加载的内容）
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.send('getTracks', myStore.getTracks())
  })

  //创建添加音乐窗口
  ipcMain.on('add-music-window', (event, argument) => {
    const addWin = new AppWindow(
      {
        width: 500,
        height: 400,
        parent: mainWindow
      },
      'add'
    )
  })

  //选择音乐文件
  ipcMain.on('open-music-file', event => {
    dialog
      .showOpenDialog({
        properties: ['openFile', 'multiSelections'],
        filters: [[{ name: 'Music', extensions: ['mp3'] }]]
      })
      .then(files => {
        if (files) {
          event.sender.send('selected-file', files.filePaths)
        }
      })
  })

  //添加文件存储
  ipcMain.on('add-tracks', (event, tracks) => {
    const updateTracks = myStore.addTrack(tracks).getTracks()
    mainWindow.send('getTracks', updateTracks)
  })

  ipcMain.on('delete-track', (event, trackId) => {
    const updateTracks = myStore.delTracks(trackId).getTracks()
    event.sender.send('getTracks', updateTracks)
  })
})

class AppWindow extends BrowserWindow {
  constructor (config, fileName) {
    const baseConfig = {
      width: 800,
      height: 600,
      webPreferences: {
        nodeIntegration: true, //是否允许渲染进程直接访问 Node.js API（如 require()、process、fs 模块等）
        preload: path.join(__dirname, `renderer/${fileName}.js`) // 通过预加载暴露必要 API
      }
    }
    config = { ...baseConfig, ...config }
    super(config)
    if (fileName == null) fileName = 'index'
    this.loadFile(`./renderer/${fileName}.html`)
    //优化窗口显示，等待页面完全加载并渲染完成后再显示窗口
    this.once('ready-to-show', () => {
      this.show()
    })
  }
}
